from lviewer.gui import viewerform
from lviewer.builder import LatexBuilder
import sys
import wx
import cgi


class LatexViewer( viewerform.LatexViewer ):
    def __init__(self, parent):
        super( LatexViewer, self ).__init__( parent )
        self.filename = sys.argv[1]

        self.pages_list.Bind( wx.EVT_LISTBOX, self.change_page )
        self.Bind( wx.EVT_CLOSE, self.on_close )
        self.builder = LatexBuilder(self.filename)
        self.builder.changed.add_listener(self.new_data)
        self.current_page_id = 0

        self.new_data()

    def on_close(self, evt):
        self.builder.stop()
        del self.builder
        self.Destroy()

    def change_page(self, evt):
        self.current_page_id = evt.GetInt()

        self.reload_data()

    def new_data(self):
        self.reload_data()
        if self.builder.good:
            self.tabs.SetSelection(0)
        else:
            self.tabs.SetSelection(1)

    def reload_data(self):
        self.pages_list.Clear()

        for idx, page in enumerate(self.builder.images):
            self.pages_list.Append( str(idx) )

        if self.current_page_id < len(self.builder.images):
            self.pages_list.SetSelection( self.current_page_id )

        if self.current_page_id < len(self.builder.images):
            bitmap = wx.Image(self.builder.images[self.current_page_id], wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        else:
            bitmap = wx.EmptyBitmap(width = 0, height = 0)

        self.current_page.SetBitmap( bitmap )

        self.pdflatex_output.SetPage( self.builder.latex_output )
        self.convert_output.SetPage( self.builder.convert_output )

    
